const mlt_dbconf = require('../util/dbconfig.js')

//获取用户信息
const test01 = function(req,res){
	let sql = `select * from user`;
	let sqlArr = [];
	let callBack = function(err,data){
		if(err) console.log('有问题，不能连接')
		else res.send({ 'list': data })
	}
	mlt_dbconf.sqlConnect(sql,sqlArr,callBack);
}

//登录接口
const login = function(req,res){
	let username = req.query.username ? req.query.username : 1;
	let phone = req.query.phone;
	let password = req.query.password;
	let sql = `select * from user where username=? or phone=? and password=?`;
	let sqlArr = [username,phone,password];
	let callBack = function(err,data){
		if(err) res.send({ 'code': 400,'msg': '连接出错，未能查询'})
		else if(data == "") res.send({ 'code': 400,'msg': '账号或密码出错！','data':[]})
		else res.send({ 'code': 200,'msg': '登录成功','data': data[0]})
	}
	mlt_dbconf.sqlConnect(sql,sqlArr,callBack);
}

//根据分类id查询other表
const getOtherInfo = function(req,res){
	let {id} = req.query;
	let sql = `select * from otherinfo where other_parentCate = ?`;
	let sqlArr = [id];
	let callBack = function(err,data){
		if(err) console.log('有问题，不能连接')
		else res.send({ 'code': 200,'msg': '加载成功','data': data})
	}
	mlt_dbconf.sqlConnect(sql,sqlArr,callBack);
}

//根据关键字查询商品表
const searchGood = function(req,res){
	let text = (req.query.text != undefined) ? req.query.text :  '';
	let sql = `select * from goodinfo where good_name like '%' ? '%' or good_label like '%' ? '%'`;
	let sqlArr = [text,text];
	let callBack = function(err,data){
		if(err) console.log('有问题，不能连接')
		else res.send({ 'code': 200,'msg': '搜索完成','data': data})
	}
	mlt_dbconf.sqlConnect(sql,sqlArr,callBack);
}

//商品页面
const findGood = function(req,res){
	let p1 = req.query.p1;
	let p2 = req.query.p2;
	let p3 = req.query.p3;
	
	p1 === undefined ? p1 = ' ORDER BY RAND()' : p1 = ' where good_type = ' + p1;
	p2 === undefined ? p2 = ' ' : (p1 == ' ORDER BY RAND()' ? p2 = " where good_label like" + "\'" + "%" + p2 + "%" + "\'" :  p2 = " where good_label like" + "\'" + "%" + p2 + "%" + "\'",p1= p1.replace('where','and'));
	p3 === undefined ? p3 = ' ' : (p1 == ' ORDER BY RAND()' ? p1='ORDER BY '+p3+' desc' : p1+=' ORDER BY '+p3+' desc');
	
	let sql = `select * from goodinfo` + p2 + p1;
	let sqlArr = [];
	let callBack = function(err,data){
		if(err) console.log('有问题，不能连接')
		// else res.send({'data': data})
		else res.send({ 'code': 200,'msg': '加载成功','data': data})
	}
	mlt_dbconf.sqlConnect(sql,sqlArr,callBack);
}

module.exports = {
	test01,
	login,
	getOtherInfo,
	searchGood,
	findGood
}
	
